<template>
  <div class="patient-medication-record">
    <!-- 头部区域 -->
    <div class="record-header">
      <h2><el-icon><FirstAidKit /></el-icon> 我的用药记录</h2>
      <div class="header-actions">
        <el-date-picker
            v-model="recordDate"
            type="month"
            placeholder="选择月份"
            format="YYYY年MM月"
            value-format="YYYY-MM"
            @change="loadMedicationData"
            style="width: 150px;"
        />
      </div>
    </div>

    <!-- 当前用药提醒 -->
    <el-card class="current-medication">
      <template #header>
        <div class="card-header">
          <el-icon><Bell /></el-icon> 当前用药提醒
        </div>
      </template>
      <div class="medication-list">
        <div v-for="(item, index) in currentMedications" :key="index" class="medication-item">
          <div class="medication-name">{{ item.name }}</div>
          <div class="medication-detail">
            <span class="dosage">{{ item.dosage }}{{ item.dosageUnit }}</span>
            <span class="frequency">{{ item.frequency }}</span>
            <span class="route">{{ item.route }}</span>
          </div>
          <div class="medication-time">
            <span class="time">{{ formatTime(item.times) }}</span>
          </div>
          <div class="medication-status">
            <el-tag :type="item.status === '进行中' ? 'success' : 'info'" size="small">
              {{ item.status }}
            </el-tag>
          </div>
        </div>
      </div>
    </el-card>

    <!-- 用药记录 -->
    <el-card class="medication-history">
      <template #header>
        <div class="card-header">
          <el-icon><Notebook /></el-icon> 用药记录
        </div>
      </template>
      <el-table
          :data="filteredMedications"
          style="width: 100%"
          v-loading="loading"
      >
        <el-table-column prop="name" label="药品名称" width="150" />
        <el-table-column prop="category" label="类别" width="100">
          <template #default="{ row }">
            <el-tag :type="getCategoryTagType(row.category)" size="small">
              {{ row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用法用量" width="180">
          <template #default="{ row }">
            {{ row.dosage }}{{ row.dosageUnit }} {{ row.frequency }}
          </template>
        </el-table-column>
        <el-table-column prop="indication" label="用途" show-overflow-tooltip />
        <el-table-column label="用药时间" width="220">
          <template #default="{ row }">
            {{ formatDate(row.startDate) }} 至 {{ row.endDate ? formatDate(row.endDate) : '长期' }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === '进行中' ? 'success' : 'info'" size="small">
              {{ row.status }}
            </el-tag>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20]"
          :total="totalMedications"
          layout="total, sizes, prev, pager, next"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 用药注意事项 -->
    <el-card class="medication-notice">
      <template #header>
        <div class="card-header">
          <el-icon><Warning /></el-icon> 用药注意事项
        </div>
      </template>
      <div class="notice-content">
        <div v-for="(notice, index) in medicationNotices" :key="index" class="notice-item">
          <div class="notice-title">{{ notice.title }}</div>
          <div class="notice-desc">{{ notice.description }}</div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { FirstAidKit, Bell, Notebook, Warning } from '@element-plus/icons-vue'
import dayjs from 'dayjs'

// 模拟数据
const generateMockData = () => {
  const categories = ['抗生素', '降压药', '降糖药', '镇痛药', '激素类', '维生素']
  const drugs = [
    '阿莫西林', '头孢克肟', '氨氯地平', '美托洛尔', '二甲双胍', '胰岛素',
    '布洛芬', '对乙酰氨基酚', '泼尼松', '维生素D', '奥美拉唑', '阿司匹林'
  ]
  const routes = ['口服', '静脉注射', '肌肉注射', '皮下注射', '外用']
  const statuses = ['进行中', '已完成', '已取消']
  const times = ['08:00', '12:00', '18:00', '22:00']

  return Array.from({ length: 30 }, (_, i) => ({
    id: i + 1,
    name: drugs[Math.floor(Math.random() * drugs.length)],
    category: categories[Math.floor(Math.random() * categories.length)],
    dosage: `${Math.floor(Math.random() * 500) + 50}`,
    dosageUnit: ['mg', 'g', 'ml'][Math.floor(Math.random() * 3)],
    frequency: ['每日1次', '每日2次', '每日3次', '每12小时1次'][Math.floor(Math.random() * 4)],
    route: routes[Math.floor(Math.random() * routes.length)],
    indication: ['上呼吸道感染', '高血压', '糖尿病', '关节炎', '胃炎'][Math.floor(Math.random() * 5)],
    startDate: dayjs().subtract(Math.floor(Math.random() * 30), 'day').format('YYYY-MM-DD'),
    endDate: dayjs().add(Math.floor(Math.random() * 30), 'day').format('YYYY-MM-DD'),
    notes: ['饭后服用', '空腹服用', '避免饮酒', '监测血压'][Math.floor(Math.random() * 4)],
    status: statuses[Math.floor(Math.random() * statuses.length)],
    times: [times[Math.floor(Math.random() * times.length)]]
  }))
}

// 数据状态
const medications = ref(generateMockData())
const filteredMedications = ref([])
const currentMedications = computed(() => medications.value.filter(item => item.status === '进行中'))
const loading = ref(false)
const recordDate = ref(dayjs().format('YYYY-MM'))
const currentPage = ref(1)
const pageSize = ref(10)
const totalMedications = computed(() => medications.value.length)

// 用药注意事项
const medicationNotices = ref([
  {
    title: '阿莫西林',
    description: '请按时服用，避免与牛奶同服，如出现皮疹请立即停药并就医'
  },
  {
    title: '氨氯地平',
    description: '每日固定时间服用，服药期间避免葡萄柚及其制品'
  },
  {
    title: '二甲双胍',
    description: '餐后服用可减少胃肠道不适，定期监测肾功能'
  }
])

// 初始化加载数据
onMounted(() => {
  filterMedications()
})

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  filterMedications()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  filterMedications()
}

// 过滤和分页数据
const filterMedications = () => {
  loading.value = true
  let result = medications.value

  filteredMedications.value = result.slice(
      (currentPage.value - 1) * pageSize.value,
      currentPage.value * pageSize.value
  )
  loading.value = false
}

// 加载用药数据
const loadMedicationData = () => {
  console.log('加载用药数据:', recordDate.value)
  filterMedications()
}

// 药品类别标签样式
const getCategoryTagType = (category) => {
  const map = {
    '抗生素': 'danger',
    '降压药': 'warning',
    '降糖药': 'success',
    '镇痛药': 'info',
    '激素类': ''
  }
  return map[category] || ''
}

// 日期格式化
const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : '-'
}

// 时间格式化
const formatTime = (times) => {
  return times ? times.join('、') : '-'
}
</script>

<style scoped>
.patient-medication-record {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.record-header h2 {
  margin: 0;
  display: flex;
  align-items: center;
}

.record-header .el-icon {
  margin-right: 8px;
}

.current-medication {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
  display: flex;
  align-items: center;
}

.card-header .el-icon {
  margin-right: 8px;
}

.medication-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.medication-item {
  padding: 15px;
  border-radius: 4px;
  background-color: #f8f8f8;
  display: flex;
  flex-direction: column;
}

.medication-name {
  font-weight: bold;
  margin-bottom: 8px;
  font-size: 16px;
}

.medication-detail {
  display: flex;
  gap: 10px;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.medication-time {
  margin-bottom: 8px;
  font-size: 14px;
}

.medication-time .time {
  color: #409EFF;
  font-weight: bold;
}

.medication-status {
  margin-top: auto;
}

.medication-history {
  margin-bottom: 20px;
}

.medication-notice {
  margin-bottom: 20px;
}

.notice-content {
  padding: 10px 0;
}

.notice-item {
  margin-bottom: 15px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.notice-item:last-child {
  border-bottom: none;
  margin-bottom: 0;
  padding-bottom: 0;
}

.notice-title {
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.notice-desc {
  color: #666;
  line-height: 1.5;
}

.el-pagination {
  margin-top: 20px;
  justify-content: center;
}

@media (max-width: 768px) {
  .medication-list {
    grid-template-columns: 1fr;
  }

  .record-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>
